package krow.dev.contest.controller;

import java.io.*;
import java.net.*;
import java.util.*;

import javax.xml.parsers.*;

import krow.dev.contest.model.*;

import org.w3c.dom.*;
import org.xmlpull.v1.*;

import android.content.*;
import android.os.*;
import android.util.*;

public class RssReader extends AsyncTask<Void, Void, Boolean>{

	
	private ArrayList<String> arInfoXml = new ArrayList<String>();
		
	private Context mContext;
	
	
	
	private MyProgressDialog mLoadDialog;
	
	private List<MenuItem> mMenuItemList;
	
	private OnCompletionListener mCompletionListener;
	
	private boolean mIsCancelled;
	
	public RssReader(Context context) {

		mContext = context;
		
		
		
		mMenuItemList = new ArrayList<MenuItem>();
	}
	
	public void setCompletionListener(OnCompletionListener completionListener){
		
		mCompletionListener = completionListener;
	}
	
	public void addMenu(int icon, String name, String rssAddr){
		
		MenuItem menuItem = new MenuItem();
		menuItem.setResourceId(icon);
		menuItem.setName(name);
		menuItem.setRssAddr(rssAddr);
		
		mMenuItemList.add(menuItem);
	}
	
	public void cancel(){
		
		mIsCancelled = true;
	}
	
	@Override
	protected void onPreExecute() {
		
		mLoadDialog = MyProgressDialog.show(mContext, "업데이트 중..", null, true, true, new DialogInterface.OnCancelListener() {
			
			@Override
			public void onCancel(DialogInterface dialog) {
				// TODO Auto-generated method stub
				
				mLoadDialog.dismiss();
			}
		});
		
	}

	@Override
	protected Boolean doInBackground(Void... params) {
		
		String dataInfoXml = "";
		
		boolean isSucceed = true;
		StringBuilder RssXml = new StringBuilder();
		
		
		try {	
			
				boolean initem = false;
				
			 	System.out.println("아이템 리스트 사이즈 - " + mMenuItemList.size() + "(15개 나와야함)");
				for(int i = 0; i < mMenuItemList.size(); i++) {
					MenuItem menuItem2 = mMenuItemList.get(i);
					
					Log.d("RssReader", menuItem2.getName() + " 파싱작업시작됨");
					
					Log.i("RssReader", menuItem2.getRssAddr());
					
					
					URL url = new URL(menuItem2.getRssAddr());
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();
					if (conn != null) {
						conn.setConnectTimeout(10000);
						conn.setUseCaches(false);
						
						if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
							BufferedReader br = new BufferedReader(
									new InputStreamReader(conn.getInputStream(), "euc-kr"));
							for (;;) {
								String line = br.readLine();
								if (line == null) {
									break;
								}
								RssXml.append(line + '\n');
							}
							br.close();
							dataInfoXml = RssXml.toString();
							arInfoXml.add(dataInfoXml);
						}
						conn.disconnect();
					}
					//System.out.println(dataInfoXml);
					
					//System.out.println(arInfoXml.get(i));
					/*
					DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
					DocumentBuilder builder = factory.newDocumentBuilder();
					//InputStream istream = new ByteArrayInputStream(dataInfoXml.getBytes("euc-kr"));
					InputStream istream = new ByteArrayInputStream(arInfoXml.get(0).getBytes("euc-kr"));
					
					
					Document doc = builder.parse(istream);
					
					Element findItemNode = doc.getDocumentElement();
					
					// item 노드의 갯수, 즉 몇개의 아이템을 카운팅하기 위한 코드
					NodeList itemCount = findItemNode.getElementsByTagName("item");
					int a = itemCount.getLength();
					menuItem2.setCount(a);
					System.out.println(menuItem2.getName() + " - " + itemCount.getLength());
					/*
					XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
					XmlPullParser parser = factory.newPullParser();
					//parser.setInput(new StringReader(arInfoXml.get(i)));
					parser.setInput(new StringReader(dataInfoXml));
					
					int eventType = parser.getEventType();
					while(eventType != XmlPullParser.END_DOCUMENT) {
						switch(eventType) {
						case XmlPullParser.START_DOCUMENT:
							break;
							
						case XmlPullParser.END_DOCUMENT:
							break;
							
						case XmlPullParser.START_TAG:
							if(parser.getName().equals("item")) {
								
								initem = true;
							}
							break;
						
						case XmlPullParser.END_TAG:
							break;
							
						case XmlPullParser.TEXT:
							if(initem) {
								//parser.get
								menuItem2.increaseCount();
								initem = false;
							}
							break;
						}
						eventType = parser.next();
						
					}
					*/
					
					
					
					//System.out.println(arInfoXml.get(i));
					Log.d("RssReader", "파싱작업 종료");
					
					
				}
				System.out.println("어레이리스트 크기 - " + arInfoXml.size());
				int num = arInfoXml.size();
				for(int x = 0; x < 3; x++) {
					System.out.println(arInfoXml.get(x));
				
					/*
					MenuItem menuItem3 = mMenuItemList.get(x);
					String s = arInfoXml.get(x);
					
					DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
					DocumentBuilder builder = factory.newDocumentBuilder();
					//InputStream istream = new ByteArrayInputStream(dataInfoXml.getBytes("euc-kr"));
					InputStream istream = new ByteArrayInputStream(s.getBytes("euc-kr"));
					
					
					Document doc = builder.parse(istream);
					
					Element findItemNode = doc.getDocumentElement();
					
					// item 노드의 갯수를 카운팅하기 위한 코드
					NodeList itemCount = findItemNode.getElementsByTagName("item");
					int a = itemCount.getLength();
					menuItem3.setCount(a);
					System.out.println(menuItem3.getName() + " - " + itemCount.getLength());
					*/
				}
				
				
				//System.out.println("params - " + params.length);
				
				
					
			
			
		} 
		catch (Exception e) {
			//isSucceed = false;
			Log.e("RssReader", e.getMessage());
		}
		
		return isSucceed;
	}
	
	@Override
	protected void onPostExecute(Boolean result) {
		
		if (mLoadDialog != null) {
			mLoadDialog.dismiss();
		}

		if (result && !mIsCancelled) {
			if (mCompletionListener != null) {
				mCompletionListener.onCompletion(mMenuItemList);
			}
		}
	}
	
	public interface OnCompletionListener {

		public abstract void onCompletion(List<MenuItem> menuItemList);
	}
}